package ua.at.tsvetkov.samizdat.data;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import ua.at.tsvetkov.samizdat.Const;
import ua.at.tsvetkov.samizdat.database.ContentProviderSamizdat;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import ua.at.tsvetkov.util.Log;

public class AsyncTaskGenre extends AsyncTask<Void, Integer, Void> {

	private Context			context;

	private int					allLineSize;
	private int					lineCounter;
	private ContentValues	genreValues;
	private Boolean			endWithError	= false;

	public AsyncTaskGenre(Service context) {
		this.context = context;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();

	}

	@Override
	protected Void doInBackground(Void... params) {
		InputStream is = null;
		InputStreamReader br = null;
		BufferedReader in = null;
		try {
			HttpURLConnection connection;
			URL url = new URL(Url.getGenresUrl());
			connection = (HttpURLConnection) url.openConnection();
			connection.setConnectTimeout(Const.TIMEOUT * 15 * 10);
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
			connection.setRequestProperty("User-Agent", "Android reader");
			is = connection.getInputStream();
			br = new InputStreamReader(is, Const.ENCODING);
			in = new BufferedReader(br, 12000);

			lineCounter = 0;
			allLineSize = 0;

			while (true) {
				genreValues = new ContentValues();
				lineCounter++;
				String[] stsWR = split(in.readLine(), 3);

				if (stsWR == null) {
					break;
				}

				if (stsWR.length == 3 && stsWR[0].length() > 0) {
					genreValues.put(Const.NAME, stsWR[0]);
					genreValues.put(Const.CODE, stsWR[1]);
					genreValues.put(Const.AMOUNT, stsWR[2]);
					context.getContentResolver().insert(ContentProviderSamizdat.GENRE_CONTENT_URI, genreValues);
				}
			}
			connection.disconnect();
		} catch (Exception e) {
			if (e instanceof FileNotFoundException) {
				endWithError = true;
				Intent broadcastIntent = new Intent(Const.BROADCAST_MESSAGE).putExtra(Const.SERVER_IS_UNAVAILABLE, Const.SERVER_IS_UNAVAILABLE);
				context.sendBroadcast(broadcastIntent);
			}
			Log.e(e);
		}
		Log.v("Download complete.");
		return null;
	}

	private static String[] split(String st, int count) {
		if (st != null) {
			String[] data = st.split("\\|");
			if (data.length == count) {
				return data;
			} else {
				String[] newData = new String[count];
				if (data.length < count)
					count = data.length;
				for (int i = 0; i < count; i++) {
					newData[i] = data[i];
				}
				for (int i = data.length; i < newData.length; i++) {
					newData[i] = "";
				}
				return newData;
			}
		} else {
			return null;
		}
	}
	
	public Boolean isEndWithError(){
		return endWithError;
	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		((Service) context).stopSelf();
	}

	@Override
	protected void onProgressUpdate(Integer... progress) {
		super.onProgressUpdate(progress);
	}

}
